import { request } from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
    /**
   * 页面的初始数据
   */
  data: {
    tabs:[{
      id:0,
      name:'综合',
      isActive:true
    },
    {
      id:1,
      name:'销量',
      isActive:false
    },
    {
      id:2,
      name:'详情',
      isActive:false
    }
  ], 
  goodsList:[]
  },
  queryinfo:{
    query:'',
    cid:'',
    pagenum:1,
    pagesize:10
  },
 
  totalpages:1,  //总页数
  //生命周期函数--监听页面加载
 // options解释url地址中的参数
  onLoad: function (options) {
    this.queryinfo.cid = options.cid||"";
    this.queryinfo.query=options.query||"";
    this.getGoodsList();
  },
  //获取商品信息
  async getGoodsList(){
    const res = await request({url:'/goods/search',data:this.queryinfo})
    const total = res.total;
    this.totalpages = Math.ceil(total / this.queryinfo.pagesize);
    //console.log(totalpages);
    this.setData({
      goodsList:[...this.data.goodsList,...res.goods],
    })

    //下拉刷新请求结束，关闭下拉框
    wx.stopPullDownRefresh();
      
  },
  //tab栏点击事件
  itemChange(e){
    //console.log(e);
    const {index} = e.detail;
    const list = this.data.tabs;
    list.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
    this.setData({
      tabs:list
    })
  },
  //页面上滑  滚动条到底部事件
  onReachBottom (){
   // console.log('页面触底')
    //如果当前页数大于等于总页数，相当于没有数据
    if(this.queryinfo.pagenum>=this.totalpages){
     // console.log(this.totalpages)
      wx.showToast({
        title: '没有下一页数据',
      });  
    }else{
      this.queryinfo.pagenum++;
      this.getGoodsList();
     // console.log(this.queryinfo)
    }
  },

  //下拉刷新事件
  onPullDownRefresh(){
    // 1.重置数组
    this.setData({
      goodsList:[]
    })
    //2.重置页码
    this.queryinfo.pagenum=1;
    // 3.重新 发送请求
    this.getGoodsList();
  }
})